<?php defined('SYSPATH') or die('No direct script access.');

class Model_Coupon extends ORM
{  
    const COUPONS_PER_PAGE = 10; 
    protected $_reload_on_wakeup = false;

    public function mark_products()
    {
        if (!$this->discount_percent && !$this->discount_value) {
            return 0;    
        }
        
        $conditions = array();
        if ($this->products_condition) {
            $tmp = explode("\n", $this->products_condition);
            foreach ($tmp as $item) {
                if (!$item) {
                    continue;
                }
                list($field, $condition, $value) = explode(';', trim($item));
                $conditions[] = array(
                    'field'     => $field,
                    'condition' => $condition,
                    'value'     => $value,
                );
            }
        }
        
        $products = DB::select('id', 'price')
                        ->from('products')
                        ->where('shop_id', '=', $this->shop_id);
        foreach ($conditions as $condition) {
            $products->where($condition['field'], $condition['condition'], DB::expr($condition['value']));    
        }
        $products = $products->execute()
                        ->as_array();
        
        $i = 0;                
        foreach ($products as $product) {
            $price = $this->get_discount_price($product['price']);
            //echo $product['id'].' - '.$product['price'].' - '.$price."\n";
            try {
                DB::insert('product_coupons', array('product_id', 'coupon_id', 'price'))
                        ->values(array($product['id'], $this->id, $price))->execute(); 
                $i++;    
            }  catch (Database_Exception $e) {
                if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
                    //continue;
                } else {
                    die($e->getMessage());
                }
            }
        }
        return $i;                
    } 
    
    public function get_discount_price($price)
    {
        if (!$this->discount_percent && !$this->discount_value) {
            throw new Model_Exception('Discount error');    
        } 
        if ($this->discount_percent) {
            $discount = $price*($this->discount_percent/100);
            return $price - $discount;    
        }  
        if ($this->discount_value) {
            return $price - $this->discount_value;        
        } 
    } 
    
    public function get_product_discount_price(Model_Product $product)
    {
        return $this->get_discount_price($product->price);
    }
    
    public function get_coupons_by_product(Model_Product $product)
    {
        // TODO cache
        $product_coupons = DB::select()
                            ->from('product_coupons')
                            ->where('product_id', '=', $product->id)
                            ->execute()
                            ->as_array();
                            
        if (!count($product_coupons)) {
            return null;
        }
        $ids = array();
        foreach ($product_coupons as $item) {
            $ids[$item['coupon_id']] = $item['coupon_id'];   
        }
        $date = new DateTime();
        $coupons = $prices = array();
        $tmp_coupons = ORM::factory('coupon')
                        ->where('id', 'IN', $ids)
                        ->where('end_date', '>', $date->format('Y-m-d H:i:s'))
                        ->find_all()
                        ->as_array();
                        
        foreach ($product_coupons as $item) {
            $prices[$item['coupon_id']] = $item; 
        }
        foreach ($tmp_coupons as $coupon) {
            $coupons[$prices[$coupon->id]['price']] = $coupon;    
        }
        ksort($coupons);
        return $coupons;                        
    }
    
    public function get_coupons_by_products($products)
    {
        // TODO cache
        if (!count($products)) {
            return null;
        }
        $date = new DateTime();
        $ids  = array();
        foreach ($products as $product) {
            $ids[$product->id] = $product->id;    
        }
        
        $product_coupons = DB::select()
                            ->from(array('product_coupons', 'pc'))
                            ->where('product_id', 'IN', $ids)
                            //->where('coupon_id', 'IN', DB::expr('(SELECT id FROM coupons WHERE end_date > '.$date->format('Y-m-d H:i:s').')'))
                            ->where('price', '=', DB::expr('(SELECT MIN(price) FROM product_coupons WHERE product_id = pc.product_id
                                            AND coupon_id IN (SELECT id FROM coupons WHERE end_date > \''.$date->format('Y-m-d H:i:s').'\'))'))        
                            ->execute()
                            ->as_array();    
        if (!count($product_coupons)) {
            return null;
        }
        $ids = $all_ids = array();
        foreach ($product_coupons as $item) {
            $ids[$item['product_id']] = $item['coupon_id'];
            $all_ids[$item['coupon_id']] = $item['coupon_id'];    
        }
        
        $coupons = array();
        $all_coupons = ORM::factory('coupon')
                        ->where('id', 'IN', $all_ids)
                        //->where('end_date', '>', $date->format('Y-m-d H:i:s'))
                        ->find_all()
                        ->as_array();  
        $all_coupons = Model_Main::process_array($all_coupons);
        
        foreach ($ids as $product_id => $coupon_id) {
            if (isset($all_coupons[$coupon_id])) {
                $coupons[$product_id] = $all_coupons[$coupon_id];
            }      
        }
        return $coupons;
    }
    
    public function get_all_actual_coupons()
    {
        $date = new DateTime();
        $coupons = ORM::factory('coupon')
                        ->where('end_date', '>', $date->format('Y-m-d H:i:s'))
                        ->find_all()
                        ->as_array();
        return $coupons;    
    }
    
    public function get_popular_coupons()
    {
        $date = new DateTime();
        $coupons = ORM::factory('coupon')
                        ->where('end_date', '>', $date->format('Y-m-d H:i:s'))
                        ->where('shop_id', 'IN', array(4102, 1001))
                        ->order_by('shop_id', 'DESC')                       
                        ->find_all()
                        ->as_array();
        return $coupons;    
    }
    
    public function get_coupons($shop = null, $count = false)
    {                
        $shop_id = $shop;
        if ($shop instanceof Model_Shop) {
            $shop_id = $shop->id;    
        }
        
        if ($coupons = Cache::instance()->get('coupons_'.$shop_id.'_'.$count)) {
            return $coupons;
        }
         
        $query = ORM::factory('coupon'); 
        
        if (!is_null($shop_id)) {
            $query->where('shop_id', '=', $shop_id);    
        }
        
        $date = new DateTime();
        $query->where('end_date', '>', $date->format('Y-m-d H:i:s'));
        
        if ($count) {
            $result = $query->count_all();
            Cache::instance()->set('coupons_'.$shop_id.'_'.$count, $result);
            return $result;
        } 
        
        $query->order_by('start_date', 'DESC');      
        
        $coupons = $query->find_all()->as_array();  
        Cache::instance()->set('coupons_'.$shop_id.'_'.$count, $coupons); 
        return $coupons;
    } 
    
    public function get_url()
    {
        $url   = $this->gotolink;
        $subid = Model_Main::get_subid(null, $this);
        if (strstr($this->gotolink, 'actionpay.ru') !== false) {
            $url = str_replace('/subaccount/', '/'.$subid.'/', $url);
        }
        if (strstr($this->gotolink, 'admitad.com') !== false) {        
            //return str_replace('/?ulp=', '/subid/'.$subid.'/?ulp=', $this->url);
            if (strstr($this->gotolink, 'subaccount') !== false) {
                $url = str_replace('subaccount', $subid, $url);
            } else {
                $url = $this->gotolink.'?subid='.$subid;
            }
        }
        if (strstr($this->gotolink, 'cpl1.ru') !== false) {
            $url = str_replace('/subaccount', '/'.$subid, $url);
        }   
        return $url;    
    }
}